package cc.chenwenxi.sdk.rainbow;

import java.util.HashMap;
import java.util.Map;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinPwmOutput;
import com.pi4j.io.gpio.RaspiPin;

import cn.hutool.core.convert.Convert;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

public class RgbKit {
	private static Map<String, GpioPinPwmOutput> pwmOutputPins;

	static {
		pwmOutputPins = new HashMap<String, GpioPinPwmOutput>();
		GpioController gpio = GpioFactory.getInstance();
		pwmOutputPins.put("redPwmPin", gpio.provisionSoftPwmOutputPin(RaspiPin.GPIO_27));
		pwmOutputPins.put("greenPwmPin", gpio.provisionSoftPwmOutputPin(RaspiPin.GPIO_28));
		pwmOutputPins.put("bluePwmPin", gpio.provisionSoftPwmOutputPin(RaspiPin.GPIO_29));
	}

	public RgbKit() {

		// Set PWM range
//		pwmOutputPins.get("redPwmPin").setPwmRange(100);
//		pwmOutputPins.get("greenPwmPin").setPwmRange(100);
//		pwmOutputPins.get("bluePwmPin").setPwmRange(100);
//
//		// Set default PWM values
//		pwmOutputPins.get("redPwmPin").setPwm(0);
//		pwmOutputPins.get("greenPwmPin").setPwm(0);
//		pwmOutputPins.get("bluePwmPin").setPwm(0);
	}

	public void shutdown() {
		pwmOutputPins.get("redPwmPin").setShutdownOptions(true);
		pwmOutputPins.get("greenPwmPin").setShutdownOptions(true);
		pwmOutputPins.get("bluePwmPin").setShutdownOptions(true);
		
	}

	public void setRgb(Rgb rgb) {
		pwmOutputPins.get("redPwmPin").setPwm(Convert.toInt(rgb.getRed(), 0));
		pwmOutputPins.get("greenPwmPin").setPwm(Convert.toInt(rgb.getGreen(), 0));
		pwmOutputPins.get("bluePwmPin").setPwm(Convert.toInt(rgb.getBlue(), 0));
	}

	public Rgb getRgb() {
		GpioPinPwmOutput redPwm = pwmOutputPins.get("redPwmPin");
		GpioPinPwmOutput greenPwm = pwmOutputPins.get("greenPwmPin");
		GpioPinPwmOutput bluePwm = pwmOutputPins.get("bluePwmPin");
		return new Rgb(redPwm.getPwm(), greenPwm.getPwm(), bluePwm.getPwm());
	}

	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	public static class Rgb {
		private Integer red;
		private Integer green;
		private Integer blue;
	}
}